<template>
  <div class="gl_heightFull">
    <div class="gl_searchBox gl_mb_15">
      <el-row :gutter="20">
        <el-col :md="4" :lg="4">
          <p>物品名称</p>
          <el-input v-model="Api_GET_ClubMaterialQO.Filter" placeholder="请输入物品名称" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <el-col :md="4" :lg="4">
          <p>状态</p>
          <el-select v-model="isfollow" size="mini" @change="gettablelist()">
            <el-option label="全部" value="" />
            <el-option v-for="(item, index) in dict.materialStatus" :key="index" :label="item.value" :value="item.code" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <p>入库时间</p>
          <el-date-picker
            v-model="tableDate"
            size="mini"
            style="width:100%"
            type="daterange"
            range-separator="至"
            start-placeholder="入库开始日期"
            end-placeholder="入库结束日期"
            value-format="yyyy-MM-dd"
            @change="changeDate"
          />
        </el-col>
        <el-col :span="4" class="search_btn">
          <!-- 查询按钮 -->
          <el-button type="primary" size="mini" @click="gettablelist()">筛选</el-button>
          <!-- 重置按钮 -->
          <el-button type="warning" size="mini" @click="clickReset()">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="nav">
      <el-button type="primary" icon="el-icon-circle-plus-outline" style="margin-bottom:15px" size="mini" @click="addstudent()">新增物资</el-button>
      <el-table v-loading="tableLoading" class="gl_table_noBorder" :data="tableData" size="mini">
        <el-table-column type="index" label="序号" align="center" width="55" />
        <el-table-column label="物品名称" prop="name" />
        <el-table-column label="颜色型号及数量" width="450">
          <template slot-scope="{row}">
            <div v-for="(item,index) in row.inventories" :key="index">
              <span class="box_color">
                {{ item.color }}
              </span>
              <span class="box_color">
                {{ item.size }}
              </span>
              <span class="box_color">
                {{ item.count }}
              </span>

            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{ row }">
            <div v-for="(item, index) in dict.materialStatus" :key="index">
              {{ row.statusCode === item.code?item.value:'' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center">
          <template slot-scope="{ row }">
            <div v-if="row.creationTime">
              {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作员" prop="creatorName" align="center" />
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button v-if="row.statusCode === 'Enable'" type="text" size="mini" @click="sequestration(row)">封存</el-button>
            <el-button v-else type="text" size="mini" @click="open(row)">启用</el-button>
            <el-button type="text" size="mini" @click="post(row)">编辑</el-button>
            <el-button type="text" size="mini" @click="cldelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- // 新增物资 -->
    <el-dialog
      :title="title"
      class="gl_dialog_TitleLine gl_dl_footer"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="930px"
    >
      <el-form ref="ruleForm" class="gl_form_mini" :model="CreateMaterialInput" :rules="rules" style="padding: 0 0px" label-width="90px">
        <div>
          <div>
            <el-form-item label="物资名称" prop="name">
              <el-input v-model="CreateMaterialInput.name" style="width:230px" placeholder="请输入物资名称" maxlength="15" size="mini" type="text" />
            </el-form-item>
            <div>
              <el-row v-for="(item,index) in CreateMaterialInput.inventories" :key="index" :gutter="20">
                <el-col :span="6">
                  <el-form-item label="颜色" :prop="'inventories.'+index+'.color'" :rules="[{ required: true,message :'请输入颜色',trigger:'blur'}, { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }]">
                    <el-input v-model="item.color" style="width:160px" placeholder="请输入颜色" maxlength="10" size="mini" type="text" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="型号" :prop="'inventories.'+index+'.size'" :rules="[{ required: true,message :'请输入型号',trigger:'blur'}, { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }]">
                    <el-input v-model="item.size" style="width:160px" placeholder="请输入型号" maxlength="10" size="mini" type="text" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="数量" :prop="'inventories.'+index+'.count'" :rules="[{ required: true,message :'请输入数量',trigger:'blur'},{ type: 'number', message: '数量必须为数字值'},{ pattern: /^\+?[1-9]\d*$/, message: '请输入大于0的正整数'} ]">
                    <el-input v-model.number="item.count" style="width:160px" placeholder="请输入数量" maxlength="5" size="mini" type="text" />
                  </el-form-item>
                </el-col>
                <el-col :span="5" class="search_btn">
                  <el-button type="danger" :disabled="index === 0" size="mini" @click="deleteCoach(index)">删除</el-button>
                  <el-button type="primary" size="mini" @click="add(index)">新增</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
          <el-form-item label="状态" prop="statusCode">
            <el-radio-group v-model="CreateMaterialInput.statusCode">
              <el-radio label="Enable">启用</el-radio>
              <el-radio label="Mothball">封存</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="tosubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="Api_GET_ClubMaterialQO.Page"
        :page-size="Api_GET_ClubMaterialQO.MaxResultCount"
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { Api_GET_ClubMaterialQO, CreateMaterialInput, UpdateMaterialInput } from '@/lib/form/hall/swaggerForm';
import { api_GET_ClubMaterial, api_POST_ClubMaterial, api_PUT_ClubMaterial, api_DELETE_ClubMaterialId } from '@/extend/api/hallswaggerApi/app';
export default {
  data() {
    return {
      materialId: '',
      title: '新增物资',
      zong: [],
      total: 0,
      UpdateMaterialInput: new UpdateMaterialInput(),
      CreateMaterialInput: new CreateMaterialInput(),
      Api_GET_ClubMaterialQO: new Api_GET_ClubMaterialQO(),
      btnLoading: false,
      dialogVisible: false,
      tableLoading: false,
      isfollow: '',
      tableDate: [], // 录入时间
      tableData: [],
      rules: {
        name: [
          { required: true, message: '请输入物资名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        statusCode: [
          { required: true, message: '请选择状态', trigger: 'change' }

        ]

      }

    };
  },

  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    dialogVisible: {
      deep: true,
      handler(val) {
        if (!val) {
          this.$refs['ruleForm'].resetFields();
          this.CreateMaterialInput = new CreateMaterialInput();
          this.CreateMaterialInput.inventories = [{}];
          this.CreateMaterialInput.statusCode = 'Enable';
        }
      }
    }
  },
  created() {
    this.getDict();
    this.gettablelist();
    this.CreateMaterialInput.statusCode = 'Enable';
    this.CreateMaterialInput.inventories.push({});
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    gettablelist(page) {
      this.Api_GET_ClubMaterialQO.Page = page || 1;
      this.Api_GET_ClubMaterialQO.Sorting = 'creationTime DESC';
      this.Api_GET_ClubMaterialQO.SkipCount = (this.Api_GET_ClubMaterialQO.Page - 1) * this.Api_GET_ClubMaterialQO.MaxResultCount;
      this.Api_GET_ClubMaterialQO.IncludeInventories = true;
      this.Api_GET_ClubMaterialQO.StatusCode = this.isfollow;
      this.tableLoading = true;
      api_GET_ClubMaterial(this.Api_GET_ClubMaterialQO).then(res => {
        this.tableLoading = false;
        this.tableData = res.items;
        this.total = res.totalCount;
        // for (var i = 0; i < this.tableData.length; i++) {
        //   this.zong.push({});
        //   for (var j = 0; j < this.tableData[i].inventories.length; j++) {
        //     this.zong[i].color = this.tableData[i].inventories[j].color;
        //     if (this.tableData[i].inventories[j + 1].color !== this.tableData[i].inventories[j].color) {
        //       this.zong[i].push;
        //     }
        //   }
        // }
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 切换录入日期
    changeDate (val) {
      const _start = val ? val[0] + ' 00:00:00' : null;
      const _end = val ? val[1] + ' 23:59:59' : null;
      this.Api_GET_ClubMaterialQO.StartTime = _start; // type: string
      this.Api_GET_ClubMaterialQO.EndTime = _end; // type: string
      this.gettablelist();
    },
    // 新增
    add(index) {
      this.CreateMaterialInput.inventories.push({});
    },
    // 删除
    deleteCoach(index) {
      this.CreateMaterialInput.inventories.splice(index, 1);
    },
    tosubmit(formName) {
      for (var i = 0; i < this.CreateMaterialInput.inventories.length; i++) {
        for (var j = i + 1; j < this.CreateMaterialInput.inventories.length; j++) {
          if (this.CreateMaterialInput.inventories[i].color === this.CreateMaterialInput.inventories[j].color && this.CreateMaterialInput.inventories[i].size === this.CreateMaterialInput.inventories[j].size) {
            this.$message({ type: 'warning', message: '无法录入相同颜色与规格物资' });
            return;
          }
        }
      }

      if (this.title === '新增物资') {
        this.CreateMaterialInput.inventories = this.CreateMaterialInput.inventories.map((item, index) => {
          item.sortOrder = index;
          return item;
        });
        this.$refs[formName].validate((valid) => {
          this.btnLoading = true;
          if (valid) {
            api_POST_ClubMaterial(this.CreateMaterialInput).then(res => {
              this.$message({ type: 'success', message: '新增成功' });
              this.btnLoading = false;
              this.dialogVisible = false;
              this.gettablelist();
            }, error => {
              this.btnLoading = false;
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          } else {
            this.btnLoading = false;
            console.log('error submit!!');
            return false;
          }
        });
      } else {
        this.CreateMaterialInput.inventories = this.CreateMaterialInput.inventories.map((item, index) => {
          item.sortOrder = index;
          item.materialId = this.materialId;
          return item;
        });
        this.$refs[formName].validate((valid) => {
          this.btnLoading = true;
          if (valid) {
            api_PUT_ClubMaterial(this.CreateMaterialInput).then(res => {
              this.$message({ type: 'success', message: '编辑成功' });
              this.btnLoading = false;
              this.dialogVisible = false;
              this.gettablelist();
            }, error => {
              this.btnLoading = false;
              const _msg = error.error.message || error.message;
              that.$message({ type: 'error', message: _msg });
            });
          } else {
            this.btnLoading = false;
            console.log('error submit!!');
            return false;
          }
        });
      }
    },
    addstudent() {
      this.dialogVisible = true;
      this.title = '新增物资';
    },
    cldelete(row) {
      this.tableLoading = true;
      const that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubMaterialId(row.id).then(res => {
            that.$message({ type: 'success', message: '删除成功' });
            that.gettablelist();
          }, error => {
            this.tableLoading = false;
            const _msg = error.error.message || error.message;
            that.$message({ type: 'error', message: _msg });
          });
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 重置
    clickReset() {
      this.isfollow = '';
      this.tableDate = [];
      this.Api_GET_ClubMaterialQO = new Api_GET_ClubMaterialQO();
      this.gettablelist();
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.Api_GET_ClubMaterialQO.MaxResultCount = MaxResultCount;
      this.gettablelist();
    },
    pageIndexChange(currentPage) {
      this.gettablelist(currentPage);
    },
    // 启用
    open(row) {
      this.tableLoading = true;
      this.UpdateMaterialInput.id = row.id;
      this.UpdateMaterialInput.statusCode = 'Enable';
      this.UpdateMaterialInput.name = row.name;
      this.UpdateMaterialInput.isUpdateInventories = false;
      api_PUT_ClubMaterial(this.UpdateMaterialInput).then(res => {
        this.gettablelist();
        this.$message({ type: 'success', message: '启用成功' });
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        that.$message({ type: 'error', message: _msg });
      });
    },
    // 封存
    sequestration(row) {
      this.tableLoading = true;
      this.UpdateMaterialInput.id = row.id;
      this.UpdateMaterialInput.statusCode = 'Mothball';
      this.UpdateMaterialInput.name = row.name;
      this.UpdateMaterialInput.isUpdateInventories = false;
      api_PUT_ClubMaterial(this.UpdateMaterialInput).then(res => {
        this.gettablelist();
        this.$message({ type: 'success', message: '封存成功' });
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        that.$message({ type: 'error', message: _msg });
      });
    },
    // 编辑
    post(row) {
      console.log(row);
      this.materialId = row.id;
      this.CreateMaterialInput = new CreateMaterialInput();
      this.CreateMaterialInput.name = row.name; // type: string
      this.CreateMaterialInput.statusCode = row.statusCode; // type: string
      for (var i = 0; i < row.inventories.length; i++) {
        this.CreateMaterialInput.inventories.push({});
        this.$set(this.CreateMaterialInput.inventories[i], 'color', row.inventories[i].color);
        this.$set(this.CreateMaterialInput.inventories[i], 'size', row.inventories[i].size);
        this.$set(this.CreateMaterialInput.inventories[i], 'count', row.inventories[i].count);
        this.$set(this.CreateMaterialInput.inventories[i], 'materialId', row.inventories[i].materialId);
        this.$set(this.CreateMaterialInput.inventories[i], 'id', row.inventories[i].id);
      }
      this.CreateMaterialInput.id = row.id;
      this.CreateMaterialInput.isUpdateInventories = true;
      this.title = '编辑物资';
      this.dialogVisible = true;
    }

  }

};
</script>

<style scoped>
.box_color {

     margin-right: 10px;

}
</style>
